﻿using SqlPerfomance.V2.DomainModel.Models;
using SqlPerfomance.V2.DomainModel.NodeTree;
using SqlPerfomance.V2.DomainModel.NodeTree.Interfaces;
using SqlPerfomance.V2.Helpers;
using System;

namespace SqlPerfomance.V2.DAL
{
	public class CommonTreeRepository : AbstractRepository<CommonTreeNode>
	{
		private int _countInRow;
		private int _totalCount;
		private int _count;
		private int _depth;

		public ITree<CommonTreeNode> CreateCommonTree(int totalCount, int depth)
		{
			var alTree = NodeTree<CommonTreeNode>.NewTree();
			_totalCount = totalCount;
			_depth = depth;
			_count = totalCount;

			ITree<CommonTreeNode> alTreeRoot = alTree;
			var alTopNode = new CommonTreeNode()
			{
				Id = 1,
				Name = "root",
				Parent_Id = null
			};
			INode<CommonTreeNode> alTop = alTreeRoot.AddChild(alTopNode);

			_count--;
			_countInRow = totalCount / depth;//totalCount / depth; // TODO: Магическое число - сколько дочерних элементов у узла
			AddItem(alTop);

			return alTree;
		}

		private void AddItem(INode<CommonTreeNode> alNode)
		{
			if (_count > 0 && alNode.Depth < _depth - 1)
			{
				for (int i = 0; i < _countInRow; i++)
				{
					if (_count > 0)
					{
						var adjancyListNewNode = new CommonTreeNode()
						{
							Id = _totalCount - _count + 1,
							Name = RandomStrings.GetRandomString(new Random().Next(5, 15)),
							Parent_Id = alNode.Data.Id
						};
						alNode.AddChild(adjancyListNewNode);

						_count--;
					}
				}
				INode<CommonTreeNode> n = alNode.Child;
				for (; n != null; n = n.Next)
				{
					AddItem(n);
				}
			}
		}
	}
}
